package cn.gov.nblr.top.sso;


import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;












import com.docMan.dao.pojo.DocDirectory;
import com.docMan.dao.pojo.Tchuman;
import com.docMan.service.DocAdminService;
import com.docMan.service.DocDirectoryService;
import com.docMan.service.TchumanService;
import com.docMan.service.TcroleService;
import com.docMan.utils.CastUtil;
import com.docMan.utils.FinalConfig;
import com.docMan.utils.SpringContextUtils;

import cn.gov.nblr.top.sso.beans.SsoUserInfo;
import cn.gov.nblr.top.sso.utils.AxisUtil;
import cn.gov.nblr.top.sso.utils.HttpUtil;
import cn.gov.nblr.top.sso.utils.SoaEncrypt;

/**
 * 閺夆晛娲﹂幎銈夋晸閿燂拷 SSO闁谎嗩嚙缂嶅秵顨ュ畝鍐
 */

public class SsoFilter implements Filter {

	public static final Logger logger = Logger.getLogger(SsoFilter.class);
	public static final String SSO_LOGIN_URL = SsoConfig.getSsoLoginUrl();// 闁告艾楠歌ぐ鎾儌鐠囪尙绉垮Δ鐘茬焷閻﹀寰勬潏顐バ曢悹鍝勭枃濞村摙RL
	public static final String SSO_TOKEN_NAME = SsoConfig.getSsoTokenName();// SSO濞寸姰鍊楁晶婵嬪触瀹ュ泦锟�	
	private String ignorePattern;
	private static TcroleService tcroleService=null;
	private static TchumanService tchumanService=null;
	private static DocAdminService docAdminService=null;
	private static DocDirectoryService docDirectoryService=null;
	static{
		tcroleService=(TcroleService) SpringContextUtils.getObject("tcroleService");
		tchumanService=(TchumanService) SpringContextUtils.getObject("tchumanService");
		docAdminService=(DocAdminService) SpringContextUtils.getObject("docAdminService");
		docDirectoryService=(DocDirectoryService) SpringContextUtils.getObject("docDirectoryService");
	}
/*	//濞撴碍绻嗙粋鍡椻枖閵娿儱寮�
	private TchumanService tchumanService;
	private LoginService loginService;*/
	
/*	public void setTchumanService(TchumanService tchumanService) {
		this.tchumanService = tchumanService;
	}

	public void setLoginService(LoginService loginService) {
		this.loginService = loginService;
	}*/

	public void init(FilterConfig filterConfig) throws ServletException {
		this.ignorePattern = filterConfig.getInitParameter("ignorePattern");
	}

	public void destroy() {}

	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		if (request.getRequestURI().matches(ignorePattern)) {
			chain.doFilter(request, response);
		} else {
			String token = request.getParameter(SSO_TOKEN_NAME);
			if (token!=null&&!"".equals(token)) {
				HttpUtil.addCookie(response, SSO_TOKEN_NAME, token, request.getContextPath(), -1, "");
			} else {
				token = HttpUtil.getCookieByName(request, SSO_TOKEN_NAME);
			}
			if (token!=null&&!"".equals(token)) {
				token = URLDecoder.decode(token,"UTF-8");
				SsoUserInfo ssoUserInfo = authenticate(request, token);
				if (ssoUserInfo != null) {
					authorize(request, ssoUserInfo);
					chain.doFilter(request, response);
					return;
				}
			}
			String clientUrl = HttpUtil.getClientUrl(request, SSO_TOKEN_NAME);
			if (logger.isDebugEnabled()) {
				logger.debug("sso redirect to login page, client url: " + clientUrl);
			}
			String redirectUrl = SSO_LOGIN_URL + "?url="+ URLEncoder.encode(clientUrl, "UTF-8");
			response.sendRedirect(redirectUrl);
		}
	}
	
	/**
	 * 闁谎嗩嚙缂嶅秹寮介敓鐘靛矗
	 * @param request
	 * @param token 濞寸姰鍊楁晶锟�	 * @return
	 */
	@SuppressWarnings("unchecked")
	protected SsoUserInfo authenticate(HttpServletRequest request, String token) {
		if (logger.isDebugEnabled()) {
			logger.debug("sso authenticate request, token: " + token);
		}
		if (token!=null&&!"".equals(token)) {
			String securityKey=SsoConfig.getSecurityKey();//闁告梻濮捐閻庨潧鏀癳y
			String webUrl=SsoConfig.getSsoWebServiceUrl();//闁兼儳鍢茶ぐ鍣杄bservice闁汇劌澧梤l
			String nameSpace=SsoConfig.getSsoWebServiceNameSpace();//闁兼儳鍢茶ぐ鍣杄bservice闁汇劌瀚幊锟犲触瀹ュ洠鏁勯柨鐕傛嫹
			String method=SsoConfig.getSsoWebServiceMethodAppLogin();
			//long TimeOut=Long.parseLong(SsoWebServiceConfig.getSsoWebServiceTimeOut());
			String securityCode=SsoConfig.getSecurityCode();
			String enSecurityCode= SoaEncrypt.encrypt(securityCode, securityKey);		
			String userIp = HttpUtil.getClientIp(request);
			Object[] args=new Object[]{token,userIp,enSecurityCode};
			Class[] resultClass=new Class[]{SsoUserInfo.class}; 
			//閻犲鍟伴弫顦漞bService鐎电増顨呴崺宀勬偨閵婏箑鐓�
			Object[] result=null;
			try {
				//閻犲洭鏀遍惇鐧bService
				result=AxisUtil.invokeService(webUrl,nameSpace,method,args,resultClass,5000);
			} catch (Exception e) {
				e.printStackTrace();
			}
			if(result!=null&&result[0]!=null){ 
				//鐎电増顨呴崺宀�媼閵堝牏妲堥柣鈧妽閸╋拷
				SsoUserInfo ssoUserInfo=(SsoUserInfo) result[0];
				return ssoUserInfo;
			}
		}
		return null;
	}
	
	/**
	 * 闁烩偓鍔嶉崺娑㈠箳閸喐缍�
	 * @param request
	 * @param ssoUserInfo
	 */
	protected void authorize(HttpServletRequest request, SsoUserInfo ssoUserInfo) {
		String token = ssoUserInfo.getToken();
		String userId = SoaEncrypt.decrypt(token, SsoConfig.getSecurityKey());
		if (logger.isDebugEnabled()) {
			logger.debug("sso authorize to user, userId: " + userId);
		}
		System.out.println(userId+"111111111111111");
		
		List<Tchuman> tchumans=tchumanService.findNoCache("select h from Tchuman h where h.userid=?", userId);
		HttpSession session = request.getSession();
		System.out.println("1111111111111111");
		if(tchumans.size()>0){
			tcroleService.getRole(tchumans.get(0).getHumanid());
			docAdminService.isAdmin();
//			tcroleService.isAdmin();
			DocDirectory personalDisk=docDirectoryService.createPersonalDirectory();
			session.setAttribute(FinalConfig.SESSION_HUMANID, tchumans.get(0).getHumanid());
			session.setAttribute(FinalConfig.PersonalDirId, personalDisk.getId());
			System.out.println(session.getAttribute(FinalConfig.SESSION_HUMANID)+"222");
		}
		System.out.println(session.getAttribute(FinalConfig.SESSION_HUMANID)+"1111");
		/*tchumanService = (TchumanService) SpringUtil.getBean("tchumanServiceImpl");
		loginService = (LoginService) SpringUtil.getBean("loginServiceImpl");
		HttpSession session = request.getSession();
		Tchuman tchuman = new Tchuman();
		tchuman.setUid(userId);
		LoginPerson loginPerson = tchumanService.findPersonDetailBytchuman(tchuman);
		//tchuman=oaqianruService.findtchumanbyTchuman(tchumanService.findHumanidBytchuman(tchuman));
		//int role=loginService.login(tchuman);
		int role = loginService.getRole(loginPerson);*/
		/*loginPerson.setRole(role);
		session.setAttribute("loginPerson", loginPerson);*/
	}

}
